# coding: utf-8
"""
将html文件转换为pdf文件（多进程）
需要npm install electron-pdf
"""
import glob
import multiprocessing
import os
import subprocess
from multiprocessing import freeze_support

import tqdm

# HTML所在文件夹
target_dir = "D:\\1"


def convert(html):
    target_pdf_o = os.path.basename(html).split(".html")[0] + ".pdf"
    if target_pdf_o in os.listdir(target_dir):
        return ""
    target_pdf = os.path.join(target_dir, target_pdf_o)
    # print(command.format(html_dir, os.path.basename(html), target_pdf))
    p = subprocess.Popen(["electron-pdf.cmd", os.path.basename(html), target_pdf])
    try:
        p.wait(30)
    except subprocess.TimeoutExpired:
        p.kill()


if __name__ == "__main__":
    html_lst = glob.glob("*.html")
    freeze_support()
    cpus = multiprocessing.cpu_count()
    with multiprocessing.Pool(cpus) as p:
        # 输出进度条
        r = list(tqdm.tqdm(p.imap(convert, html_lst[::-1])))

    # 单进程
    """
    for html in tqdm.tqdm(html_lst):
        target_pdf_o = os.path.basename(html).split('.html')[0] + '.pdf'
        if target_pdf_o in os.listdir(target_dir):
            continue
        target_pdf = os.path.join(target_dir, target_pdf_o)
        # print(command.format(html_dir, os.path.basename(html), target_pdf))
        p = subprocess.Popen(
            ['electron-pdf.cmd',
            os.path.basename(html), target_pdf])
        try:
            p.wait(30)
        except subprocess.TimeoutExpired:
            p.kill()
    """
